package Follow

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"log"
	"time"
	//"time"
)

type Follow struct {
	controllers.MainController
}

type Follower struct {
	Uid string `json:"uuid"` //被关注人的ID
}

func (this *Follow) Post() {
	uuid := this.Ctx.GetCookie("uuid")
	rd := redis.R.Conn
	defer rd.Close()
	userid, _ := rd.Get(uuid)
	if userid == "" {
		body := map[string]interface{}{"code": "300", "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	t := time.Now().UTC().Format("2006-01-02")
	r := this.Ctx.Request
	var F Follower
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&F)
	if err != nil {
		body := map[string]interface{}{"code": "300", "data": "请求异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//执行关注表操作 userid --关注-->Uid
	follow(userid, F.Uid, t)
	fans(F.Uid, userid, t)
	//执行粉丝表操作  Uid ---拥有粉丝-->userid
	body := map[string]interface{}{"code": "200", "data": "操作成功"}
	this.Data["json"] = body
	this.ServeJSON()
}

func follow(u, f, t string) {
	fc := redis.R.FollowConn
	_, err1 := fc.HSet(u, f, t)
	if err1 != nil {
		log.Fatal(err1)
	}
	fc.Close()
}

func fans(f, u, t string) {
	fsc := redis.R.FansConn
	_, err2 := fsc.HSet(f, u, t)
	if err2 != nil {
		log.Fatal(err2)
	}
	fsc.Close()
}
